package com.code2roc.jarmanage.servlet.manage;

import com.code2roc.jarmanage.bizloigc.ProjectBizloigc;
import com.code2roc.jarmanage.db.CommandDB;
import com.code2roc.jarmanage.db.GroupDB;
import com.code2roc.jarmanage.db.ProjectDB;
import com.code2roc.jarmanage.db.WarDB;
import com.code2roc.jarmanage.model.*;
import com.code2roc.jarmanage.util.*;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ExportServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap paramMap = CommonUtil.getParamMap(req);
        String projectIDList = ConvertUtil.convert2String(paramMap.get("projectIDList"));
        String type = ConvertUtil.convert2String(paramMap.get("type"));
        String xmlFileName = "";
        String tag = CommonUtil.getDateTagToSecond();
        String exportFolderPath = "tempfiles/exportmanage/";
        File exportFolder = new File(exportFolderPath);
        if (!exportFolder.exists()) {
            exportFolder.mkdirs();
        }
        Document doc = DocumentHelper.createDocument();
        Element root = doc.addElement("ExportData");
        Element filetype = root.addElement("filetype");

        List<ProjectDO> projectDOList = new ArrayList<>();
        List<WarDO> warDOList = new ArrayList<>();
        List<GroupDO> groupDOList = new ArrayList<>();
        List<String> groupGuidList = new ArrayList<>();
        List<CommandDO> commandDOList = new ArrayList<>();
        String[] projectIDArray = projectIDList.split(";");
        for (String projectID : projectIDArray) {
            String groupGuid = "";
            if (type.equals("jar")) {
                filetype.setText("jarconfig");
                ProjectDO projectDO = ProjectDB.selectOne(projectID);
                projectDOList.add(projectDO);
                groupGuid = projectDO.getGroupGuid();

            } else if (type.equals("war")) {
                filetype.setText("warconfig");
                WarDO warDO = WarDB.selectOne(projectID);
                warDOList.add(warDO);
                groupGuid = warDO.getGroupGuid();
            }

            if (!StringUtil.isEmpty(groupGuid) && !groupGuidList.contains(groupGuid)) {
                GroupDO groupDO = GroupDB.selectOne(groupGuid);
                groupDOList.add(groupDO);
                groupGuidList.add(groupGuid);
            }
            List<CommandDO> commandDBList = ProjectBizloigc.getCommondList(projectID);
            if (commandDBList.size() > 0) {
                commandDOList.addAll(commandDBList);
            }
        }
        if (type.equals("jar")) {
            appendEntityList(root, projectDOList, "DepolyProject");
        } else if (type.equals("war")) {
            appendEntityList(root, warDOList, "DepolyProject");
        }
        appendEntityList(root, groupDOList, "DepolyGroup");
        appendEntityList(root, commandDOList, "ExecuteCommand");
        String xmlName = "jarmanage-export-" + tag + ".xml";
        xmlFileName = exportFolder.getAbsolutePath() + File.separator + xmlName;
        OutputFormat format = OutputFormat.createPrettyPrint();
        format.setEncoding("utf-8");
        Writer out;
        out = new FileWriter(xmlFileName);
        XMLWriter writer = new XMLWriter(out, format);
        writer.write(doc);
        writer.close();

        result.add("fileid", tag);
        resp.getWriter().println(result.toString());
    }

    private void appendEntityList(Element root, List entityList, String tableName) {
        try {
            if (entityList.size() > 0) {
                Element elementList = root.addElement("DataEntityList");
                for (Object entity : entityList) {
                    Element element = elementList.addElement("DataEntity");
                    element.addAttribute("tableName", tableName);
                    for (Field field : entity.getClass().getDeclaredFields()) {
                        if (!Modifier.isStatic(field.getModifiers())) {
                            field.setAccessible(true);
                            Element fieldElement = element.addElement(field.getName());
                            fieldElement.setText(ConvertUtil.convert2String(field.get(entity)));
                        }
                    }
                }
            }
        } catch (Exception e) {
            LogUtil.error(e);
        }
    }
}
